const mqtt = require('mqtt');

// 连接到公共 MQTT Broker
const client = mqtt.connect('mqtt://broker.emqx.io:1883', {
  clientId: 'test-topic-matcher-' + Math.random().toString(16).substr(2, 8),
  clean: true
});

client.on('connect', () => {
  console.log('✅ 已连接到 broker.emqx.io');

  // 先订阅 server/public
  client.subscribe('server/public', (err) => {
    if (err) {
      console.error('❌ 订阅失败:', err);
      return;
    }
    console.log('✅ 已订阅主题: server/public');

    // 等待1秒后发布消息到 device/DEV070
    setTimeout(() => {
      console.log('\n📤 发布消息到: device/DEV070');
      client.publish('device/DEV070', 'Test message from device/DEV070', { qos: 0 });

      // 再等2秒后发布到 server/public
      setTimeout(() => {
        console.log('📤 发布消息到: server/public');
        client.publish('server/public', 'Test message from server/public', { qos: 0 });

        // 再等2秒后退出
        setTimeout(() => {
          console.log('\n🔚 测试完成');
          client.end();
          process.exit(0);
        }, 2000);
      }, 2000);
    }, 1000);
  });
});

client.on('message', (topic, message) => {
  console.log(`\n📨 收到消息!`);
  console.log(`   主题: ${topic}`);
  console.log(`   内容: ${message.toString()}`);
});

client.on('error', (err) => {
  console.error('❌ MQTT 错误:', err);
  process.exit(1);
});

// 5秒超时保护
setTimeout(() => {
  console.log('⏱️ 测试超时');
  client.end();
  process.exit(0);
}, 10000);
